# -*- coding: utf-8 -*-

import table_meta as meta

class Model:
  
  def __init__(self, uri):
    
    self.db = meta.DB(uri)
    self.db.select()
    print "init..."
    
  def getTables(self):
    tables = {}
    sql = "select name, table_type from tables where active = 1 and project='kylin' order by name"
    tabs = self.db.execute(sql)
    for row in tabs:
      #print row[0]
      tables[ row[0]] = row[1]
    return tables

  def getColumns(self, table):
    """
    sql = 'show fields from sometable'
    
    Field 	Type 	Null 	Key 	Default 	Extra
    
    """
    columns = []
    sql = """select name as Field, data_type as Type, width as Length,
    attribute, column_type
    from columns where active = 1 and project='kylin' and tablename='%s' order by ordering
    """  %(table)
    #print sql
    cols = self.db.execute(sql)
    #print cols
    for row in cols:
      dict = {}
      dict['Field'] = row[0]
      dict['Type']  = row[1]
      dict['Length']  = row[2]
      dict['attribute']  = row[3]
      dict['coltype']  = row[4]
      columns.append(dict)
      #cols[ row[0]] = row[1]
      #columns[row[0]] = row[1]
    return columns
    
    
def test():
  m = Model()
  tabs = m.getTables()
  cols = m.getColumns('TAGS')
  for item in cols:
    print item
  """
  for x in  tabs:
    print x, tabs[x].encode('utf8')
    #pass
  """
  
  
if __name__ == "__main__":
  test()
